/**
 * 
 */
package com.ydy.service.good.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydy.constant.SystemConstant;
import com.ydy.exception.BusinessException;
import com.ydy.exception.DataNotFoundException;
import com.ydy.exception.ValidateException;
import com.ydy.ienum.EnumGood;
import com.ydy.mapper.SkuMapper;
import com.ydy.mapper.SpuDetailMapper;
import com.ydy.mapper.SpuMapper;
import com.ydy.model.Sku;
import com.ydy.model.Spu;
import com.ydy.model.SpuDetail;
import com.ydy.model.Staff;
import com.ydy.service.good.GoodService;
import com.ydy.utils.ValidateUtil;
import com.ydy.vo.other.BaseVo;
import com.ydy.vo.other.PageVo;
import com.ydy.vo.other.ResultVo;

import tk.mybatis.mapper.entity.Example;

/**
 * @author xuzhaojie
 *
 *         2019年5月27日 下午3:02:44
 */
@Service
@Transactional
public class GoodServiceImpl implements GoodService {
	private final static Logger log = LoggerFactory.getLogger(GoodServiceImpl.class);
	@Autowired
	private SpuMapper spuMapper;
	@Autowired
	private SkuMapper skuMapper;
	@Autowired
	private SpuDetailMapper spuDetailMapper;

	@Value("${DefaultPrice:99999.0}")
	private Double DefaultPrice;// 默认价格

	@Override
	public PageVo<Spu> select(Spu spu, Staff staff, Integer page, Integer size) {
		PageVo<Spu> vo = new PageVo<Spu>(page, size);
		Page<Spu> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "spu_id desc");
		Example example = new Example(Spu.class);
		Example.Criteria criteria = example.createCriteria();
		if (spu.getName() != null) {
			criteria.andLike("name", "%" + spu.getName() + "%");
		}
		criteria.andEqualTo("shopId", staff.getShopId());
		List<Spu> list = spuMapper.selectByExample(example);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public PageVo<Spu> list(String name, Long shopId, Integer page, Integer size) {
		PageVo<Spu> vo = new PageVo<Spu>(page, size);
		Page<Spu> pageBean = PageHelper.startPage(vo.getPage(), vo.getSize(), "up desc,spu_id desc");
		Example example = new Example(Spu.class);
		Example.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(name)) {
			criteria.andLike("name", "%" + name + "%");
		}
		criteria.andEqualTo("spuStatus", SystemConstant.GOOD_ON);
		criteria.andEqualTo("shopId", shopId);
		List<Spu> list = spuMapper.selectByExample(example);
		vo.setTotal(pageBean.getTotal());
		vo.setList(list);
		return vo;
	}

	@Override
	public Spu selectSpuByIdForUser(Long spuId) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu vo = spuMapper.selectSpuById(spuId, SystemConstant.GOOD_ON);
		if (vo == null) {
			throw new BusinessException(EnumGood.SPU_OFF);
		}
		Sku example = new Sku();
		example.setSpuId(spuId);
		example.setSkuStatus(SystemConstant.GOOD_ON);// 用户只能查到上架的sku
		PageHelper.orderBy("now_price asc");
		List<Sku> list = skuMapper.select(example);
		if (CollectionUtils.isEmpty(list)) {
			throw new BusinessException(EnumGood.SKU_EMPTY);
		}
		vo.setSkus(list);
		return vo;
	}

	@Override
	public Spu selectSpuById(Long spuId, Staff staff) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu vo = spuMapper.selectSpuById(spuId, null);
		if (vo == null) {
			throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(vo.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		Sku example = new Sku();
		example.setSpuId(spuId);
		PageHelper.orderBy("now_price asc");
		List<Sku> list = skuMapper.select(example);
		vo.setSkus(list);
		return vo;
	}

	@Override
	public Sku selectSkuById(Long skuId, Staff staff) {
		if (skuId == null) {
			throw new NullPointerException();
		}
		Sku sku = skuMapper.selectByPrimaryKey(skuId);
		if (sku == null) {
			throw new DataNotFoundException(EnumGood.SKU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(sku.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		return sku;
	}

	@Override
	public Spu saveOrUpdateSpu(Spu spu, Staff staff) {
		if (spu == null) {
			throw new NullPointerException("Spu不能为空");
		}
		// 校验数据有效
		spu.setShopId(staff.getShopId());
		Map<String, String> validateInfo = ValidateUtil.validateEntity(spu);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		Date now = new Date();
		if (spu.getSpuId() == null) {
			// TODO 分类
			spu.setCategoryId(0);
			spu.setCreateTime(now);
			spu.setUpdateTime(now);
			spu.setSpuStatus(SystemConstant.GOOD_OFF);
			if (spu.getUp() == null) {
				spu.setUp(SystemConstant.UP_OFF);
			}
			spuMapper.insertSelective(spu);
			SpuDetail detail = new SpuDetail();
			detail.setDetail(spu.getDetail());
			detail.setSpuId(spu.getSpuId());
			detail.setImages(spu.getImages());
			spuDetailMapper.insertSelective(detail);
			log.info("新增SPU成功:" + spu.getSpuId());
		} else {
			Spu temp = spuMapper.selectByPrimaryKey(spu.getSpuId());
			if (temp == null) {
				log.info("找不到SPU:" + spu.getSpuId());
				throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
			}
			spu.setUpdateTime(now);
			spuMapper.updateByPrimaryKeySelective(spu);
			SpuDetail detail = new SpuDetail();
			detail.setDetail(spu.getDetail());
			detail.setSpuId(spu.getSpuId());
			detail.setImages(spu.getImages());
			spuDetailMapper.updateByPrimaryKeySelective(detail);
			spu.setSpuStatus(temp.getSpuStatus());
			spu.setCreateTime(temp.getCreateTime());
			log.info("保存SPU成功:" + spu.getSpuId());
		}
		return spu;
	}

	@Override
	public BaseVo statusSpu(Long spuId, Staff staff) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu temp = spuMapper.selectByPrimaryKey(spuId);
		if (temp == null) {
			log.info("找不到SPU:" + spuId);
			throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		Spu spu = new Spu();
		spu.setSpuId(spuId);
		StringBuilder builder = new StringBuilder();
		if (Objects.equals(SystemConstant.GOOD_ON, temp.getSpuStatus())) {
			spu.setSpuStatus(SystemConstant.GOOD_OFF);
			builder.append("Spu下架成功:").append(spuId);
		} else {
			spu.setSpuStatus(SystemConstant.GOOD_ON);
			builder.append("Spu上架成功:").append(spuId);
		}
		spuMapper.updateByPrimaryKeySelective(spu);
		log.info(builder.toString());
		return new ResultVo();
	}

	@Override
	public BaseVo upSpu(Long spuId, Staff staff) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu temp = spuMapper.selectByPrimaryKey(spuId);
		if (temp == null) {
			log.info("找不到SPU:" + spuId);
			throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		Spu spu = new Spu();
		spu.setSpuId(spuId);
		StringBuilder builder = new StringBuilder();
		if (Objects.equals(SystemConstant.UP_ON, temp.getUp())) {
			spu.setUp(SystemConstant.UP_OFF);
			builder.append("Spu取消置顶:").append(spuId);
		} else {
			spu.setUp(SystemConstant.UP_ON);
			builder.append("Spu确认置顶:").append(spuId);
		}
		spuMapper.updateByPrimaryKeySelective(spu);
		log.info(builder.toString());
		return new ResultVo();
	}

	@Override
	public BaseVo deleteSpu(Long spuId, Staff staff) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu temp = spuMapper.selectByPrimaryKey(spuId);
		if (temp == null) {
			log.info("找不到SPU:" + spuId);
			throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		spuMapper.deleteByPrimaryKey(spuId);
		spuDetailMapper.deleteByPrimaryKey(spuId);
		Sku example = new Sku();
		example.setSpuId(spuId);
		skuMapper.delete(example);
		log.info("删除SPU成功:" + spuId);
		return new ResultVo();
	}

	@Override
	public Sku saveOrUpdateSku(Sku sku, Staff staff) {
		if (sku == null) {
			throw new NullPointerException("Sku不能为空");
		}
		// 校验数据有效
		sku.setShopId(staff.getShopId());
		Map<String, String> validateInfo = ValidateUtil.validateEntity(sku);
		if (!validateInfo.isEmpty()) {
			throw new ValidateException(validateInfo);
		}
		Date now = new Date();
		if (sku.getSkuId() == null) {
			// TODO 分类
			sku.setCategoryId(0);
			sku.setCreateTime(now);
			sku.setUpdateTime(now);
			sku.setSkuStatus(SystemConstant.GOOD_OFF);
			skuMapper.insertSelective(sku);
		} else {
			Sku temp = skuMapper.selectByPrimaryKey(sku.getSkuId());
			if (temp == null) {
				log.info("找不到SKU:" + sku.getSkuId());
				throw new DataNotFoundException(EnumGood.SKU_NOT_FOUND);
			}
			sku.setUpdateTime(now);
			sku.setSkuStatus(temp.getSkuStatus());
			skuMapper.updateByPrimaryKeySelective(sku);
		}
		Sku example = new Sku();
		example.setSpuId(sku.getSpuId());
		List<Sku> list = skuMapper.select(example);
		if (CollectionUtils.isEmpty(list)) {
			throw new BusinessException(EnumGood.SKU_EMPTY);
		}
		Double minPrice = DefaultPrice;
		Double minNowPrice = DefaultPrice;
		for (Sku k : list) {
			minNowPrice = Math.min(k.getNowPrice(), minNowPrice);
			minPrice = Math.min(k.getPrice(), minPrice);
		}
		Spu spu = new Spu();
		spu.setSpuId(sku.getSpuId());
		spu.setNowPrice(minNowPrice);
		spu.setPrice(minPrice);
		spuMapper.updateByPrimaryKeySelective(spu);
		log.info("保存SKU成功:" + sku.getSkuId());
		return sku;
	}

	@Override
	public List<Sku> selectSkuBySpuId(Long spuId, Staff staff) {
		if (spuId == null) {
			throw new NullPointerException();
		}
		Spu temp = spuMapper.selectByPrimaryKey(spuId);
		if (temp == null) {
			log.info("找不到SPU:" + spuId);
			throw new DataNotFoundException(EnumGood.SPU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		Sku example = new Sku();
		example.setSpuId(spuId);
		PageHelper.orderBy("now_price asc");
		List<Sku> list = skuMapper.select(example);
		if (CollectionUtils.isEmpty(list)) {
			throw new BusinessException(EnumGood.SKU_EMPTY);
		}
		return list;
	}

	@Override
	public BaseVo statusSku(Long skuId, Staff staff) {
		if (skuId == null) {
			throw new NullPointerException();
		}
		Sku temp = skuMapper.selectByPrimaryKey(skuId);
		if (temp == null) {
			log.info("找不到SKU:" + skuId);
			throw new DataNotFoundException(EnumGood.SKU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		Sku sku = new Sku();
		sku.setSkuId(skuId);
		StringBuilder builder = new StringBuilder();
		if (Objects.equals(SystemConstant.GOOD_ON, temp.getSkuStatus())) {
			sku.setSkuStatus(SystemConstant.GOOD_OFF);
			builder.append("Sku下架成功:").append(skuId);
		} else {
			sku.setSkuStatus(SystemConstant.GOOD_ON);
			builder.append("Sku上架成功:").append(skuId);
		}
		skuMapper.updateByPrimaryKeySelective(sku);
		log.info(builder.toString());
		return new ResultVo();
	}

	@Override
	public BaseVo deleteSku(Long skuId, Staff staff) {
		if (skuId == null) {
			throw new NullPointerException();
		}
		Sku temp = skuMapper.selectByPrimaryKey(skuId);
		if (temp == null) {
			log.info("找不到SKU:" + skuId);
			throw new DataNotFoundException(EnumGood.SKU_NOT_FOUND);
		}
		if (!staff.getShopId().equals(temp.getShopId())) {
			throw new BusinessException(EnumGood.GOOD_NOT_BELONG);
		}
		skuMapper.deleteByPrimaryKey(skuId);
		log.info("删除SKU成功:" + skuId);
		return new ResultVo();
	}

}
